package com.imooc.miaosha.util;

import com.google.common.collect.Lists;
import com.imooc.miaosha.common.Const;

import redis.clients.jedis.*;
import redis.clients.util.Hashing;
import redis.clients.util.Sharded;


import java.util.List;


public class RedisPoolConfig {

    private static ShardedJedisPool shardedJedisPool;

    public static ShardedJedisPool getShardedJedisPoolInstance() {

        if (shardedJedisPool == null) {
            JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
            jedisPoolConfig.setMaxTotal(600);
            jedisPoolConfig.setMaxIdle(300);
            jedisPoolConfig.setMinIdle(5);
            jedisPoolConfig.setBlockWhenExhausted(false);
            jedisPoolConfig.setTestOnReturn(true);
            jedisPoolConfig.setMaxWaitMillis(100000);
            List<JedisShardInfo> shardInfoList = Lists.newArrayList();
            JedisShardInfo jedisShardInfo2 = new JedisShardInfo(Const.REDIS_2_CONFIG.IP, Const.REDIS_2_CONFIG.PORT, false);
            jedisShardInfo2.setPassword(Const.REDIS_2_CONFIG.PASS);
            shardInfoList.add(jedisShardInfo2);
            JedisShardInfo jedisShardInfo1 = new JedisShardInfo(Const.REDIS_1_CONFIG.IP, Const.REDIS_1_CONFIG.PORT, false);
            jedisShardInfo1.setPassword(Const.REDIS_1_CONFIG.PASS);
            shardInfoList.add(jedisShardInfo1);
            shardedJedisPool = new ShardedJedisPool(jedisPoolConfig, shardInfoList, Hashing.MURMUR_HASH, Sharded.DEFAULT_KEY_TAG_PATTERN);
            return shardedJedisPool;
        } else {
            return shardedJedisPool;
        }

    }

    public static ShardedJedis getResource() {
        ShardedJedis jedis = null;
        try {
            jedis = getShardedJedisPoolInstance().getResource();
            return jedis;
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }

    }


    public static void returnResource(Jedis jedis) {

        jedis.close();

    }

    public static void main(String[] args) {


    }


}
